import {Admin, Res, Student} from "../types";
import {getRequest} from "../utils/myAxios.ts";
import {updateAdminInfo} from "./AdminApi.ts";
import {dayjs} from "element-plus";
import {updateStudent} from "./StudentApi.ts";

//学生登录
export async function stuLogin(account:String,password:String): Res<Student> {
    const stuList = await getRequest<Array<Student>>(`/student?account=${account}&password=${password}`);
    console.log('登录结果',stuList[0])

    const loginStu = stuList[0];
    //判断loginStu的id属性是否存在
    if (stuList.length > 0 && loginStu.account === account
            && loginStu.password === password) {
        //修改登录时间
        loginStu.loginTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        updateStudent(loginStu)

        return {
            code: 200,
            data: loginStu,
            flag: true,
            msg: "登录成功"
        }
    } else {
        return {
            code: 400,
            data: null,
            flag: false,
            msg: "账号或密码错误"
        }
    }
}
//管理员登录
export async function adminLogin(account:String,password:String): Res<Admin> {
    const admins = await getRequest<Array<Admin>>(`/admin?account=${account}&password=${password}`);

    const loginStu = admins[0];
    //判断loginStu的id属性是否存在
    if (admins.length > 0 && loginStu.account === account
            && loginStu.password === password) {

        //修改登录时间
        admins[0].loginTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
        updateAdminInfo(admins[0])

        return {
            code: 200,
            data: loginStu,
            flag: true,
            msg: "登录成功"
        }
    } else {
        return {
            code: 400,
            data: null,
            flag: false,
            msg: "账号或密码错误"
        }
    }
}
